package com.guochenglang.www.controller;

import com.guochenglang.www.pojo.Dialog;
import com.guochenglang.www.pojo.User;
import com.guochenglang.www.service.DialogService;
import com.guochenglang.www.service.UserService;
import com.guochenglang.www.util.GetObject;
import com.guochenglang.www.util.MyDependency;
import com.guochenglang.www.view.vo.DialogView;
import com.guochenglang.www.web.result.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * 私聊Controller层
 *
 * @author GuoChenglang
 */

public class DialogController {
    private static final DialogService DIALOG_SERVICE = MyDependency.returnObject(DialogService.class);
    private static final UserService USER_SERVICE = MyDependency.returnObject(UserService.class);

    /**
     * 获得聊天记录
     */
    public static Result getDialog(HttpServletRequest req, HttpServletResponse resp) throws SQLException, InterruptedException, IllegalAccessException, InstantiationException {
        //获得用户id
        Integer userId = Integer.valueOf(req.getParameter("userId"));
        //获得对面用户id
        Integer anotherId = Integer.valueOf(req.getParameter("anotherId"));
        //获得所有聊天
        ArrayList<Dialog> dialogs = DIALOG_SERVICE.allDialog(userId, anotherId);
        ArrayList<DialogView> dialogViews = new ArrayList<>();
        for (Dialog dialog : dialogs) {
            //获得聊天人以及聊天信息，返回前端展示
            DialogView dialogView = new DialogView();
            User user = USER_SERVICE.getUser(dialog.getUserId());
            dialogView.setUsername(user.getUsername());
            dialogView.setDialog(dialog);
            dialogViews.add(dialogView);
        }
        return Result.result(dialogViews);
    }

    /**
     * 更新聊天状态，将已读变成未读
     */
    public static Result updateDialog(HttpServletRequest req, HttpServletResponse resp) throws SQLException, InterruptedException, IllegalAccessException, IOException {
        //获得对话id
        Integer dialogId = GetObject.getObject(req, Integer.class);
        //更新状态
        int num = DIALOG_SERVICE.updateDialog(dialogId);
        return Result.result(num);
    }
}
